package cn.edu.scau.cmi.ema.service.base;

import org.springframework.stereotype.Component;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.springframework.stereotype.Component;

@Component
public class CmiCalendarTimeEditor extends PropertyEditorSupport {
	private Calendar calendar = Calendar.getInstance();

	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		if (text.length() > 0) {
			text = text.replaceAll("T", " ");
			try {
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				Date date = simpleDateFormat.parse(text);
				calendar.setTime(date);
				setValue(calendar);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		} else
			setValue(null);
	}

	@Override
	public String getAsText() {
		Object o = super.getValue();
		if (o != null && o instanceof Calendar) {
			Calendar calendar = (Calendar) o;
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			String dateString = simpleDateFormat.format(calendar.getTime());
			dateString = dateString.replaceAll(" ", "T");
			return dateString;
		} else
			return super.getAsText();
	}

	public Calendar getCalendar() {
		return this.calendar;
	}		
}	